<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { getCouponListApi, createCouponApi, updateCouponApi, deleteCouponApi, batchDeleteCouponApi } from "@/api/coupon-manage"
import { type CouponData, type CreateCouponRequestData, type UpdateCouponRequestData } from "@/api/coupon-manage/types/coupon"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, CirclePlus, Delete, Download, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { cloneDeep } from "lodash-es"

defineOptions({
  // 命名当前组件
  name: "CouponManage"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

// 新增/修改优惠券
const DEFAULT_FORM_DATA: CreateCouponRequestData = {
  name: "",
  type: 1,
  value: 0,
  minConsume: 0,
  useStartTime: "",
  useEndTime: "",
  description: "",
  total: 1,
  issueType: 2,
  issueCondition: "",
  receiveStartTime: "",
  receiveEndTime: "",
  receiveLimitNum: 1
}

const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = ref<CreateCouponRequestData>(cloneDeep(DEFAULT_FORM_DATA))
const isUpdate = ref<boolean>(false)

const formRules: FormRules<CreateCouponRequestData> = {
  name: [{ required: true, trigger: "blur", message: "请输入优惠券名称" }],
  type: [{ required: true, trigger: "change", message: "请选择优惠券类型" }],
  value: [{ required: true, trigger: "blur", message: "请输入面值/折扣值" }],
  minConsume: [{ required: true, trigger: "blur", message: "请输入最低消费" }],
  useStartTime: [{ required: true, trigger: "change", message: "请选择使用开始时间" }],
  useEndTime: [{ required: true, trigger: "change", message: "请选择使用结束时间" }],
  total: [{ required: true, trigger: "blur", message: "请输入发行量" }, { type: "number", min: 1, message: "发行量必须大于0", trigger: "blur" }],
  issueType: [{ required: true, trigger: "change", message: "请选择发放类型" }],
  issueCondition: [{ required: true, trigger: "blur", message: "请输入发放条件" }],
  receiveStartTime: [{ required: true, trigger: "change", message: "请选择领取开始时间" }],
  receiveEndTime: [{ required: true, trigger: "change", message: "请选择领取结束时间" }],
  receiveLimitNum: [{ required: true, trigger: "blur", message: "请输入每人限领数量" }, { type: "number", min: 1, message: "每人限领数量必须大于0", trigger: "blur" }]
}

const handleCreate = () => {
  dialogVisible.value = true
  isUpdate.value = false
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}

const handleUpdate = (row: CouponData) => {
  if (row.isIssued) {
    ElMessage.warning("该优惠券已发放，无法修改")
    return
  }
  
  dialogVisible.value = true
  isUpdate.value = true
  formData.value = {
    name: row.name,
    type: row.type,
    value: row.value,
    minConsume: row.minConsume,
    useStartTime: row.useStartTime ? row.useStartTime.split(' ')[0] : '',
    useEndTime: row.useEndTime ? row.useEndTime.split(' ')[0] : '',
    description: row.description,
    total: row.total,
    issueType: row.issueType,
    issueCondition: row.issueCondition,
    receiveStartTime: row.receiveStartTime ? row.receiveStartTime.split(' ')[0] : '',
    receiveEndTime: row.receiveEndTime ? row.receiveEndTime.split(' ')[0] : '',
    receiveLimitNum: row.receiveLimitNum
  }
  ;(formData.value as UpdateCouponRequestData).id = row.id
}

const handleCreateOrUpdate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    
    // 处理时间格式：开始时间添加00:00:00，结束时间添加23:59:59
    const submitData = {
      ...formData.value,
      useStartTime: formData.value.useStartTime ? `${formData.value.useStartTime} 00:00:00` : '',
      useEndTime: formData.value.useEndTime ? `${formData.value.useEndTime} 23:59:59` : '',
      receiveStartTime: formData.value.receiveStartTime ? `${formData.value.receiveStartTime} 00:00:00` : '',
      receiveEndTime: formData.value.receiveEndTime ? `${formData.value.receiveEndTime} 23:59:59` : ''
    }
    
    const api = isUpdate.value ? updateCouponApi : createCouponApi
    api(submitData as any)
      .then(() => {
        ElMessage.success(isUpdate.value ? "修改成功" : "创建成功")
        dialogVisible.value = false
        getCouponData()
      })
      .finally(() => {
        loading.value = false
      })
  })
}

const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}

// 删除优惠券
const handleDelete = (row: CouponData) => {
  if (row.isIssued) {
    ElMessage.warning("该优惠券已发放，无法删除")
    return
  }
  
  ElMessageBox.confirm(`正在删除优惠券：${row.name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteCouponApi(row.id).then(() => {
      ElMessage.success("删除成功")
      getCouponData()
    })
  })
}

// 批量删除
const multipleTableRef = ref()
const multipleSelection = ref<CouponData[]>([])

const handleSelectionChange = (val: CouponData[]) => {
  multipleSelection.value = val
}

const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请选择要删除的优惠券")
    return
  }
  
  // 检查是否有已发放的优惠券
  const issuedCoupons = multipleSelection.value.filter(item => item.isIssued)
  if (issuedCoupons.length > 0) {
    ElMessage.warning(`选中的优惠券中有 ${issuedCoupons.length} 个已发放，无法删除已发放的优惠券`)
    return
  }
  
  ElMessageBox.confirm(`确认删除选中的 ${multipleSelection.value.length} 个优惠券？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    const ids = multipleSelection.value.map(item => item.id)
    batchDeleteCouponApi(ids).then(() => {
      ElMessage.success("批量删除成功")
      getCouponData()
    })
  })
}

// 查询优惠券数据
const couponData = ref<CouponData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  name: "",
  type: "",
  status: "",
  issueType: "",
  issueCondition: ""
})

const getCouponData = () => {
  loading.value = true
  getCouponListApi({
    pageNo: paginationData.currentPage,
    pageSize: paginationData.pageSize,
    name: searchData.name || undefined,
    type: searchData.type ? Number(searchData.type) : undefined,
    status: searchData.status ? Number(searchData.status) : undefined,
    issueType: searchData.issueType ? Number(searchData.issueType) : undefined,
    issueCondition: searchData.issueCondition || undefined
  })
    .then(({ data }) => {
      paginationData.total = data.total
      couponData.value = data.list
    })
    .catch(() => {
      couponData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}

const handleSearch = () => {
  paginationData.currentPage === 1 ? getCouponData() : (paginationData.currentPage = 1)
}

const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}

// 格式化显示
const formatCouponType = (type: number) => {
  return type === 1 ? "满减券" : "折扣券"
}

const formatIssueType = (issueType: number) => {
  return issueType === 1 ? "自动发放" : "手动领取"
}

const formatStatus = (status: number) => {
  return status === 1 ? "正常" : "失效"
}

const formatTotal = (total: number) => {
  return total.toString()
}

const formatIssueCondition = (issueCondition: string) => {
  const conditionMap: Record<string, string> = {
    'new_user': '新用户注册',
    'first_order': '首次下单',
    'activity': '活动优惠券'
  }
  return conditionMap[issueCondition] || issueCondition
}

const formatReceiveLimitNum = (receiveLimitNum: number) => {
  return receiveLimitNum.toString()
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getCouponData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="name" label="优惠券名称">
          <el-input v-model="searchData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="type" label="优惠券类型">
          <el-select v-model="searchData.type" placeholder="请选择" clearable style="width: 120px;">
            <el-option label="满减券" value="1" />
            <el-option label="折扣券" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item prop="issueType" label="发放类型">
          <el-select v-model="searchData.issueType" placeholder="请选择" clearable style="width: 120px;">
            <el-option label="自动发放" value="1" />
            <el-option label="手动领取" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item prop="issueCondition" label="发放条件">
          <el-select v-model="searchData.issueCondition" placeholder="请选择" clearable style="width: 120px;">
            <el-option label="新用户注册" value="new_user" />
            <el-option label="首次下单" value="first_order" />
            <el-option label="活动优惠券" value="activity" />
          </el-select>
        </el-form-item>
        <el-form-item prop="status" label="状态">
          <el-select v-model="searchData.status" placeholder="请选择" clearable style="width: 100px;">
            <el-option label="正常" value="1" />
            <el-option label="失效" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="handleCreate">新增优惠券</el-button>
          <el-button type="danger" :icon="Delete" @click="handleBatchDelete">批量删除</el-button>
        </div>
        <div>
          <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip>
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getCouponData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table ref="multipleTableRef" :data="couponData" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="name" label="优惠券名称" align="center" min-width="120" />
          <el-table-column prop="type" label="类型" align="center" width="80">
            <template #default="scope">
              <el-tag :type="scope.row.type === 1 ? 'success' : 'warning'" effect="plain" disable-transitions>
                {{ formatCouponType(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="value" label="面值/折扣" align="center" width="100">
            <template #default="scope">
              {{ scope.row.type === 1 ? `¥${scope.row.value}` : `${(scope.row.value * 10).toFixed(1)}折` }}
            </template>
          </el-table-column>
          <el-table-column prop="minConsume" label="最低消费" align="center" width="100">
            <template #default="scope">
              ¥{{ scope.row.minConsume }}
            </template>
          </el-table-column>
          <el-table-column prop="total" label="发行量" align="center" width="80">
            <template #default="scope">
              {{ formatTotal(scope.row.total) }}
            </template>
          </el-table-column>
          <el-table-column prop="remain" label="剩余数量" align="center" width="80" />
          <el-table-column prop="issueType" label="发放类型" align="center" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.issueType === 1 ? 'info' : 'primary'" effect="plain" disable-transitions>
                {{ formatIssueType(scope.row.issueType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="issueCondition" label="发放条件" align="center" width="100">
            <template #default="scope">
              <el-tag type="warning" effect="plain" disable-transitions>
                {{ formatIssueCondition(scope.row.issueCondition) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" align="center" width="80">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" effect="plain" disable-transitions>
                {{ formatStatus(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="useStartTime" label="有效期" align="center" width="180">
            <template #default="scope">
              {{ scope.row.useStartTime }} ~ {{ scope.row.useEndTime }}
            </template>
          </el-table-column>
          <el-table-column prop="receiveStartTime" label="领取时间" align="center" width="180">
            <template #default="scope">
              {{ scope.row.receiveStartTime }} ~ {{ scope.row.receiveEndTime }}
            </template>
          </el-table-column>
          <el-table-column prop="receiveLimitNum" label="限领数量" align="center" width="100">
            <template #default="scope">
              {{ formatReceiveLimitNum(scope.row.receiveLimitNum) }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center" width="160" />
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button 
                type="primary" 
                text 
                bg 
                size="small" 
                :disabled="scope.row.isIssued" 
                @click="handleUpdate(scope.row)"
              >
                修改
              </el-button>
              <el-button 
                type="danger" 
                text 
                bg 
                size="small" 
                :disabled="scope.row.isIssued" 
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isUpdate ? '修改优惠券' : '新增优惠券'"
      @closed="resetForm"
      width="600px"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" label-position="left">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="name" label="优惠券名称">
              <el-input v-model="formData.name" placeholder="请输入优惠券名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="type" label="优惠券类型">
              <el-select v-model="formData.type" placeholder="请选择类型" style="width: 100%">
                <el-option label="满减券" :value="1" />
                <el-option label="折扣券" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="value" :label="formData.type === 1 ? '减免金额' : '折扣值'">
              <el-input-number 
                v-model="formData.value" 
                :min="0" 
                :precision="formData.type === 1 ? 2 : 1"
                :step="formData.type === 1 ? 1 : 0.1"
                style="width: 100%"
                :placeholder="formData.type === 1 ? '请输入减免金额' : '请输入折扣值(如0.85表示8.5折)'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="minConsume" label="最低消费">
              <el-input-number v-model="formData.minConsume" :min="0" :precision="2" style="width: 100%" placeholder="请输入最低消费金额" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="useStartTime" label="使用开始时间">
              <el-date-picker
                v-model="formData.useStartTime"
                type="date"
                placeholder="请选择使用开始日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="useEndTime" label="使用结束时间">
              <el-date-picker
                v-model="formData.useEndTime"
                type="date"
                placeholder="请选择使用结束日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="total" label="发行量">
              <el-input-number v-model="formData.total" :min="1" style="width: 100%" placeholder="请输入发行量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="issueType" label="发放类型">
              <el-select v-model="formData.issueType" placeholder="请选择发放类型" style="width: 100%">
                <el-option label="自动发放" :value="1" />
                <el-option label="手动领取" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="receiveStartTime" label="领取开始时间">
              <el-date-picker
                v-model="formData.receiveStartTime"
                type="date"
                placeholder="请选择领取开始日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="receiveEndTime" label="领取结束时间">
              <el-date-picker
                v-model="formData.receiveEndTime"
                type="date"
                placeholder="请选择领取结束日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="receiveLimitNum" label="每人限领数量">
              <el-input-number v-model="formData.receiveLimitNum" :min="1" style="width: 100%" placeholder="请输入每人限领数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="issueCondition" label="发放条件">
              <el-select v-model="formData.issueCondition" placeholder="请选择发放条件" style="width: 100%">
                <el-option label="新用户注册" value="new_user" />
                <el-option label="首次下单" value="first_order" />
                <el-option label="活动优惠券" value="activity" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item prop="description" label="描述">
          <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入优惠券描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateOrUpdate" :loading="loading">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>